<template>
  <!--  新的工作台  -->
    <ExpireRemindMessage style="margin: 10px;" />
  <div class="workbench-box">
    <div class="workbench-left">
      <div class="card-box">
        <a-row :gutter="[10, 10]" :wrap="true">
          <a-col
            :span="8"
            v-if="hasContractAuth"
          >
            <ContractApprovalCard/>
          </a-col>
          <a-col
            :span="8"
            v-if="hasContractAuth"
          >
            <ExpirationContractCard/>
          </a-col>
          <a-col
            :span="8"
            v-if="hasClueAuth"
          >
            <ClueFollowUpCard/>
          </a-col>
          <a-col
            :span="8"
            v-if="hasRepairMenu && !hasClueAuth"
          >
            <WorkOrderTodoCard/>
          </a-col>
          <a-col
            :span="8"
            v-if="hasOwnerUserAuth"
          >
            <BussinessApproveCard/>
          </a-col>
          <a-col
            :span="8"
            v-if="hasMyWorkApprovalAuth"
          >
            <ApprovalCard/>
          </a-col>
          <a-col
            :span="8"
          >
            <TodoTaskCard/>
          </a-col>
        </a-row>
      </div>
      <div class="app-box">
        <div class="title-box" style="padding: 10px 14px">
          <div class="title-box-dec">常用功能</div>
          <div class="title-box-action" @click.stop="handleAppEdit">
            <cu-icon type="org-zidingyi"></cu-icon>
            <span class="ml-2">自定义</span>
          </div>
        </div>
        <div class="app-content">
          <div class="app-content-box">
            <a-row :gutter="[10, 18]" :wrap="true" v-if="appData?.length">
              <a-col
                :span="6"
                v-for="(item, index) of appData"
                :key="item.arrKey"
              >
                <div class="app-item" @click.stop="goMenuTab(item)">
                  <div class="app-left">
                    <div class="icon-box">
                      <img class="image" v-if="item.app_logo" :src="item.app_logo" />
                      <cu-icon v-else-if="item.icon" :type="item.icon"></cu-icon>
                      <cu-icon v-else type="org-menu-yingyong"></cu-icon>
                    </div>
                    <div class="app-name nowrap">{{item.name}}</div>
                  </div>
                  <div class="app-right">
                    >
                  </div>
                </div>
              </a-col>
            </a-row>
            <a-empty v-else />
          </div>
        </div>
      </div>
    </div>
    <div class="workbench-right">
      <div class="schedule-box">
        <div class="title-box" style="padding: 10px">
          <div class="title-box-dec">
            日程管理
            <a-button style="margin-left: 4px" type="link" size="small" @click.stop="goScheduleMore">
              <template #icon>
                <FullscreenOutlined/>
              </template>
              更多
            </a-button>
          </div>
          <div class="title-box-action">
            <a-button type="link" size="small" @click.stop="() => handleAddTodo(0, currentDate)">
              <template #icon>
                <cu-icon type="org-zuixing-10"></cu-icon>
              </template>
              新建日程
            </a-button>
          </div>
        </div>
        <div class="schedule-content-box">
          <!--   日程内容   -->
          <div class="calendar-box">
            <a-calendar :fullscreen="false" v-model:value="currentDate">
              <template #dateCellRender="{ current: value }">
                <template v-if="getListData(value).length">
                  <a-badge status="processing"/>
                </template>
              </template>
            </a-calendar>
          </div>
          <div class="calendar-dec">
            <div class="title-box">
              <div class="title-box-dec">
                <a-badge :count="selectDayList?.length" :offset="[15, 5]">
                  今日日程
                </a-badge>
              </div>
              <div class="title-box-action" v-if="selectDayList?.length" @click.stop="showAllTodo">
                <span class="ml-2">更多>></span>
              </div>
            </div>
            <ToDoListItem
              v-if="selectDayList?.length"
              :item="selectDayList[0]"
              :currentDate="currentDate"
              @refresh="refreshList"
              @AddSchedule="(id) => {handleAddTodo(id)}"
            />
            <div v-else class="todo-list">
              <div class="todo-list-dec nowrap">暂无更多待办事项</div>
            </div>
          </div>
        </div>

      </div>
      <div class="notice-box">
        <div class="title-box">
          <div class="title-box-dec">企业公告</div>
          <div class="title-box-action" @click.stop="goNoticeMore">
            <span class="ml-2">更多>></span>
          </div>
        </div>
        <a-empty v-if="!noticeInfo" />
        <div v-else class="notice-content">
          <div class="notice-title">
            <div class="notice-title-content">{{noticeInfo.title}}</div>
            <div class="notice-title-date">{{noticeInfo.send_time}}</div>
          </div>
          <div class="notice-dec-content">
            <div class="notice-dec-content-box">
              <div v-html="noticeInfo.content"></div>
            </div>
          </div>
        </div>
      </div>
    </div>


    <!--  自定义  -->
    <CustomAppModal
      :visible="appEditVisible"
      :collectList="appData"
      @close="appEditVisible = false"
    />

    <!--  更多日程  -->
    <a-modal
      :visible="moreTodoVisible"
      title="待办事项"
      :footer="null"
      @cancel="handleCloseMore"
      :bodyStyle="{
        maxHeight: '60%',
        overflow: 'hidden auto',
        padding: '10px 24px'
      }"
      :width="620"
      :destroyOnClose="true"
    >
      <div class="date-box">
        {{moment(currentDate).format(
          "YYYY年MM月DD日"
      )}}
      </div>
      <div v-for="(item, index) in selectDayList" :key="index" style="margin-bottom: 10px">
        <ToDoListItem
          :item="item"
          :currentDate="currentDate"
          @refresh="refreshList"
          @AddSchedule="(id) => {handleAddTodo(id)}"
        />
      </div>
    </a-modal>

  </div>
      <!-- 到期提醒  -->
    <ExpireRemind :visible="!!$store.getters.orgInfo.account.expired" />
</template>
<script>
import {computed, defineComponent, reactive, toRefs, nextTick} from "vue";
import NotVillageIndex from "@/views/home/NotVillageIndex.vue";
import VillageIndex from "@/views/home/VillageIndex.vue";
import utils from "@/common/utils/utils";
import request from "@/common/utils/request";
import CustomAppModal from "@/views/home/components/CustomAppModal.vue";
import ToDoListItem from "@/views/home/components/ToDoListItem.vue";
import moment from "moment";
import store from "@/store/index";
import ApprovalCard from "@/views/home/components/ApprovalCard.vue";
import BussinessApproveCard from "@/views/home/components/BussinessApproveCard.vue";
import ClueFollowUpCard from "@/views/home/components/ClueFollowUpCard.vue";
import ContractApprovalCard from "@/views/home/components/contractApprovalCard.vue";
import ExpirationContractCard from "@/views/home/components/ExpirationContractCard.vue";
import TodoTaskCard from "@/views/home/components/TodoTaskCard.vue";
import _ from "lodash";
import {message} from "ant-design-vue";
import {
  FullscreenOutlined,
} from "@ant-design/icons-vue";
import BLCOMMON from "bl-common-vue3";
import WorkOrderTodoCard from "@/views/home/components/workOrderTodoCard.vue";
import ExpireRemindMessage from "@/views/home/modules/ExpireRemindMessage.vue";

import ExpireRemind from "@/views/home/modules/ExpireRemind.vue";

export default defineComponent({
  name: "workbench",
  components: {
    CustomAppModal,
    ToDoListItem,
    ApprovalCard,
    BussinessApproveCard,
    ClueFollowUpCard,
    ContractApprovalCard,
    ExpirationContractCard,
    TodoTaskCard,
    FullscreenOutlined,
    WorkOrderTodoCard,
    ExpireRemindMessage,
    ExpireRemind
  },
  setup() {
    const state = reactive({
      appEditVisible: false,
      currentDate: moment(),
      scheduleList: [],
      moreTodoVisible: false,
      noticeInfo: null,
    });

    const hasClueAuth = BLCOMMON.utils.getBtnPermission([
      "clueManagement",
      "curd",
      "list",
    ]);
    const hasContractAuth = BLCOMMON.utils.getBtnPermission([
      "contractList",
      "curd",
      "list",
    ]);
    const hasOwnerUserAuth = BLCOMMON.utils.getBtnPermission([
      "ownerUser",
      "curd",
      "list",
    ]);
    const hasMyWorkApprovalAuth = BLCOMMON.utils.getBtnPermission([
      "workApprovalMyDataCenter",
      "curd",
      "list",
    ]);

    const hasRepairMenu = computed(() => {
      return !!store.getters.menuList.find((v) => v.alias == 'workOrderRepairControl');
    });

    const getListData = (value) => {
      let listData;

      state.scheduleList.length > 0 &&
      state.scheduleList.map((item) => {
        item.length > 0 &&
        item.map((i) => {
          if (
            value.year() == i.year &&
            value.month() + 1 == i.month &&
            value.date() == i.day
          ) {
            listData = i.list;
          }
        });
      });
      return listData || [];
    };

    const selectDayList = computed(() => {
      return getListData(state.currentDate);
    })

    const appData = computed(() => {
      let appList = store.getters.appList;
      let allMenu = store.getters.menuList;
      let app = [];

      let appFetchList =[]
  
      appList.forEach((alias) => {
        let menu = allMenu.find((v) => v.alias == alias);
        if (menu) {
          app.push(menu);
          appFetchList.push(menu.app)
        }
      })
      
      console.log('bailingElectronAPI', window.rawWindow?.bailingElectronAPI);
      console.log('appFetchList', appFetchList);
      if( window.rawWindow?.bailingElectronAPI && appFetchList.length > 0 ) {
        appFetchList = Array.from(new Set(appFetchList)).filter((item)=>item !='org')
        console.log('new appFetchList', appFetchList);
        appFetchList.forEach((app)=>{
          fetch(`/micro_apps/${app}/index.html?t=${new Date().getTime()}`, {
            method: 'GET',
          }).then(response => {})
        })
      }
      return app;
    });

    const menuList = computed(() => {
      return store.getters.userMenu;
    })

    const getChildByAlias = (list, alias) => {
      for (let item of list) {
        if (item.alias === alias) {
          return item;
        } else if (item.children && item.children.length > 0) {
          let result = getChildByAlias(item.children, alias);
          if (result) {
            return result;
          }
        }
      }
      return null;
    };

    const getFirstPage = (childData) => {
      if (childData?.length && childData[0]?.children?.length) {
        return getFirstPage(childData[0].children)
      } else {
        return childData[0] || {};
      }
    };

    const goMenuTab = (item) => {
      if (!item.url) {
        // 找他的子集中第一个能打开的页面
        let childData = getChildByAlias(menuList.value, item.alias);
        let firstPage = getFirstPage(childData?.children);
        if (firstPage?.url) {
          window.microApp.forceDispatch({
            type: "dispatchStore",
            dispatchName: 'SetMicroPages',
            value: {
              ...firstPage,
              name: item.name,
            },
          })
        }
      } else {
        window.microApp.forceDispatch({
          type: "dispatchStore",
          dispatchName: 'SetMicroPages',
          value: item,
        })
      }
    };

    const handleAppEdit = () => {
      state.appEditVisible = true;
    };

    const getScheduleList = () => {
      let params = {
        year: new Date(state.currentDate).getFullYear(),
        month: new Date(state.currentDate).getMonth() + 1,
        day: new Date(state.currentDate).getDate(),
      };
      request.get("work_task", "/plan", params).then((res) => {
        state.scheduleList = res.planList;
      });
    };

    const handleAddTodo = (id, currentDate) => {
      if (window.__MICRO_APP_ENVIRONMENT__) {
        window.microApp.forceDispatch({
          type: "SetChildDrawerList",
          info: {
            props: {
              title: id ? '编辑日程' : '新建日程',
              visible: true,
              maskClosable: false,
              width: 500,
              bodyStyle:{ padding: '20px 20px 80px 20px'},
              destroyOnClose: true,
            },
            microId:"workScheduleAddScheduleComponent",
            app:"workSchedule",
            url:'/allComponents/addSchedule',
            params: {
              isMainDrawer: true,
              id: id,
              addScheduleTimeStart: currentDate ? moment(currentDate).format(
                "YYYY-MM-DD HH:mm:ss"
              ) : '', // 新增日程开始时间
              addScheduleTimeEnd: currentDate ? moment(currentDate)
                .add(1, "hours")
                .format("YYYY-MM-DD HH:mm:ss") : '', // 新增日程结束时间,
              addScheduleType: currentDate ? "fullDay" : '', //新增日程类型（是否全天）
              success: () => {
                refreshList();
              },
            }
          },
        })
      }
    };

    const refreshList = () => {
      getScheduleList();
    };

    const showAllTodo = () => {
      state.moreTodoVisible = true;
    };

    const handleCloseMore = () => {
      state.moreTodoVisible = false;
    };

    const goNoticeMore = () => {
      if (window.__MICRO_APP_ENVIRONMENT__) {
        window.microApp.forceDispatch({
          type: "SetMicroPages",
          microInfo: {
            microId: `org_workbench_workNotice`,
            app: 'workNotice',
            name: `企业公告`,
            url: `/basic/noticeList`,
          }
        })
      }
    };

    const getNoticeList = () => {
      request
        .get("/work_notice", "/org/list", {
          page: 1,
          pageSize: 1,
        })
        .then((res) => {
          // todo... 处理撤回的通知
          state.noticeInfo = res?.list[0] || null;
        });
    };

    const goScheduleMore = () => {
      window.microApp.forceDispatch({
        type: "SetChildDrawerList",
        info: {
          props: {
            title: "日程",
            maskCloseable: true,
            visible: true,
            closable: true,
            width: 1300,
            bodyStyle: {height: '100%', flex: 1, padding: 0},
            destroyOnClose: true,
          },
          microId: "org_workbench_schedule",
          heightFull: true,
          app: "workSchedule",
          url: '/schedule/home',
          params: {
            isMainDrawer: true,
          }
        },
      })
    };

    const goMore = (item) => {
      if (item.microId) {
        window.microApp.forceDispatch({
          type: "SetMicroPages",
          microInfo: {
            microId: item.microId,
            app: item.app,
            name: item.name,
            url: item.url,
          }
        })
      }
    };


    const init = () => {
      getScheduleList();
      getNoticeList();
    };




    init();

    return {
      ...toRefs(state),
      selectDayList,
      appData,
      hasClueAuth,
      hasContractAuth,
      hasOwnerUserAuth,
      hasMyWorkApprovalAuth,
      hasRepairMenu,
      moment,
      handleAppEdit,
      handleAddTodo,
      getListData,
      refreshList,
      showAllTodo,
      handleCloseMore,
      goNoticeMore,
      goMore,
      goMenuTab,
      goScheduleMore,
    };
  },
});
</script>

<style lang="less" scoped>
@titleFontSize: 15px;
@cardRadius: 4px;
@cardPaddingTb: 10px;
@cardPaddingLr: 14px;
.nowrap {
  overflow: hidden;
  white-space: nowrap;
  word-break: break-all;
  text-overflow: ellipsis;
}
.workbench-box {
  width: 100%;
  min-height: 100%;
  overflow: hidden auto;
  position: relative;
  display: flex;
  padding: 10px;
  .workbench-left {
    flex: 1;
    min-width: 0;
    min-height: 0;
    padding-right: 10px;
    display: flex;
    flex-direction: column;
  }
  .workbench-right {
    width: 38%;
    display: flex;
    flex-direction: column;
    .schedule-box {
      padding: 0 0 10px 0;
      width: 100%;
      background: #fff;
      border-radius: @cardRadius;
      position: relative;
      display: flex;
      flex-direction: column;
      .schedule-content-box {
        padding: 0 10px;
        width: 100%;
        display: flex;
        flex-direction: column;
      }
    }
  }


  .app-item {
    padding: 10px 12px;
    display: flex;
    background: linear-gradient(to right, #fff, rgba(38, 129, 243, .1));
    border-radius: @cardRadius;
    height: 66px;
    align-items: center;
    border: 1px solid #e9e9e9;
    cursor: pointer;
    .app-left {
      flex: 1;
      display: flex;
      min-width: 0;
      height: 100%;
      align-items: center;
      .icon-box {
        min-width: 46px;
        max-width: 46px;
        height: 46px;
        overflow: hidden;
        border-radius: @border-radius-base;
        background: @primary-color;
        color: #fff;
        font-size: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        .image {
          width: 100%;
          height: 100%;
        }
      }
    }
    .app-name {
      height: fit-content;
      padding: 0 6px;
      font-weight: 600;
    }
  }
}

.show-more {
  color: @primary-color;
  cursor: pointer;
  font-size: 12px;
}
.card-box {
  padding-bottom: 10px;
}
.app-box {
  flex: 1;
  border-radius: @cardRadius;
  background: #fff;
  display: flex;
  flex-direction: column;
  min-height: 0;
  .app-content {
    flex: 1;
    width: 100%;
    min-height: 0;
    min-width: 0;
    position: relative;
    .app-content-box {
      position: absolute;
      padding: @cardPaddingTb @cardPaddingLr;
      width: 100%;
      height: 100%;
      overflow-y: auto;
    }
  }
}
.title-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: @cardPaddingTb 0;
  .title-box-dec {
    font-size: @titleFontSize;
    font-weight: bold;
  }
  .title-box-action {
    color: @primary-color;
    cursor: pointer;
  }
}
.todo-list {
  height: 36px;
  display: flex;
  align-items: center;
  background: #f6f6f6;
  padding: 0 10px;
  .todo-list-dec {
    flex: 1;
    min-width: 0;
  }
}

.calendar-box {
  width: 100%;
}

.notice-box {
  border-radius: @cardRadius;
  background: #fff;
  flex: 1;
  min-width: 0;
  margin-top: 10px;
  padding: 0 10px 10px 10px;
  display: flex;
  flex-direction: column;
}

:deep(.ant-picker-calendar-header) {
  justify-content: flex-start;
  padding: 0 0 12px 0;
}

:deep(.ant-picker-calendar-header .ant-picker-calendar-mode-switch) {
  display: none !important;
}
:deep(.ant-picker-calendar-date) {
  position: relative;
}
:deep(.ant-picker-calendar-date-content) {
  position: absolute;
  top: 18px;
  right: 0;
}
.date-box {
  font-size: 16px;
  padding: 6px 0;
  font-weight: 600;
  margin-bottom: 10px;
}
.notice-title {
  padding: 14px 0;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .notice-title-content {
    flex: 1;
    min-width: 0;
    font-size: 14px;
    font-weight: 600;
  }
  .notice-title-date {
    font-size: 12px;
    color: #999;
  }
}
.notice-dec-content {
  flex: 1;
  position: relative;
  width: 100%;
  min-height: 0;
  min-width: 0;
  .notice-dec-content-box {
    position: absolute;
    width: 100%;
    height: 100%;
    overflow-y: auto;
  }
}

.notice-content {
  flex: 1;
  min-height: 200px;
  min-width: 0;
  display: flex;
  flex-direction: column;
}

:deep(.ant-picker-cell) {
  padding: 12px 0;
}

:deep(.ant-btn > .anticon + span) {
  margin-left: 4px!important;
}
:deep(.notice-dec-content-box  *) {
  font-size: 12px!important;
}
</style>
